package br.gov.ifrn.model.dao;

import java.lang.annotation.Annotation;

import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import br.gov.ifrn.ws.interfaces.Dao;

public class AppDao implements Dao {

	private EntityManagerFactory emf;
	
	private EntityManager em;
	
	public AppDao() {}
	
	private boolean testIsEntity(Object o) throws ClassNotFoundException{
		Class<?> clazz = Class.forName( o.getClass().getName() );
		Annotation annotation = clazz.getAnnotation( Entity.class );
		return ( annotation != null );
	}
	
	private void preOperation(){
		emf = Persistence.createEntityManagerFactory("ns-mysql");
		em = emf.createEntityManager();
		em.getTransaction().begin();
	}
	
	private void posOperation(){
		em.getTransaction().commit();
		em = null;
		emf = null;
	}
	//*/
	
	public void persist(Object object, boolean withFlush) {
		try {
			if( !testIsEntity(object) )
				return;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		preOperation();
		em.persist(object);
		if( withFlush )
			em.flush();
		posOperation();
	}
	
	public void persist(Object object) {
		persist(object, true);
	}
	
	public Object merge(Object object, boolean withFlush) {
		try {
			if( !testIsEntity(object) )
				return null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		preOperation();
		Object response = em.merge(object);
		if( withFlush )
			em.flush();
		posOperation();
		return response;
	}
	
	public Object merge(Object object) {
		return merge(object, true);
	}
	
}
